<!--  -->
<template>
  <view class="updater">
    <!-- version text -->
    <view class="version" @tap="updateApp">{{ version || "null" }}</view>
    <!-- popup -->
    <uni-popup ref="popup" type="center" class="index-popup">
      <view class="index-dl">
        <text class="">大小：{{ formartSize(totalByte) }}</text>
        <progress :percent="progress" show-info stroke-width="3" />
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},

  props: {
    prjName: null,
  },

  data() {
    //这里存放数据
    return {
      version: null,
      progress: 0,
      totalByte: null,
      // baseUrl: 'http://192.168.68.202:9603',
      // baseUrl: 'http://apk.yywis.com',
	  // baseUrl: 'http://153.99.98.91:9989',
	  baseUrl: 'http://testurl.yywis.com:9989',
    };
  },

  computed: {
    formartSize() {
      return (num) => {
        if (num == 0) return "0 B";
        let k = 1024;
        let sizeStr = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; //容量单位
        let i = 0;
        for (let l = 0; l < 8; l++) {
          if (num / Math.pow(k, l) < 1) {
            break; //小于1跳出循环
          }
          i = l; //不小于1的话这个单位就合适或者还要大于这个单位 接着循环
        }
        return (num / Math.pow(k, i)).toFixed(3) + " " + sizeStr[i];
      };
    },
  },

  created() {
    this.getVersion();
  },

  //方法集合
  methods: {
    getVersion() {
      // this.version = plus.runtime.version;
      plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
        console.log(JSON.stringify(wgtinfo));
        this.version = wgtinfo.version;
        console.log("b版本：", wgtinfo.version); //应用版本号
      });
    },

    async updateApp() {
      if (!this.prjName) return;

      let baseUrl = this.baseUrl
      let prjName = this.prjName
      
      let ret = await this.httpUp(baseUrl + '/upload/get-version',{
        version: this.version,
        prjName,
      });

      console.log(ret.data);

      let url = baseUrl + ret.data.url;
      // return console.log(url);

      if (ret.data.flag) {
        let _this = this;
        uni.showModal({
          title: "提示",
          content: "发现新版本:" + ret.data.newVersion,
          success: function (res) {
            if (res.confirm) {
              _this.toDownload(url);
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      } else {
        uni.showToast({
          title: "已经是最新版本",
          duration: 2000,
          icon: "none",
        });
      }
    },

    toDownload(url) {
      let _this = this;
      // this.progress = 0;
      // 提示进度

      this.$refs.popup.open("center");

      let dlObj = uni.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            console.log("下载成功");
            console.log(res.tempFilePath);
            plus.runtime.install(
              plus.io.convertLocalFileSystemURL(res.tempFilePath),
              {},
              {},
              function (error) {
                uni.showToast({
                  title: "安装失败",
                  duration: 1500,
                });
              }
            );
          }
        },
      });

      dlObj.onProgressUpdate((res) => {
        console.log("下载进度" + res.progress);

        _this.progress = res.progress;
        if (!_this.totalByte) {
          _this.totalByte = res.totalBytesExpectedToWrite;
        }
      });
    },

    // http
    httpUp( apiPath, data) {
      console.log("发送的参数");
      console.log(data);
      console.log(">>>request url: " + apiPath);
      return new Promise((resolve, reject) => {
        uni.request({
          url: apiPath,
          data: data,
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded",
          },
          success: (res) => {
            // console.log('success');
            resolve(res);
          },
          fail(error) {
            console.log("error");
            console.log(error);
            reject(error);
          },
          complete() {
            // console.log('comp');
          },
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
/* 使用$符号可以标识一个变量;@import url(); 引入公共css类 */
.index-dl {
    background-color: #fff;
    color: #000;
    width: 500rpx;
    border-radius: 20rpx;
    padding: 20rpx;
  }
</style>
